var account = function() {
	var qs = new QueryString();
	var tempAccount = qs.get("customerAccount");
	if (!tempAccount) {
		tempAccount = getManagerUser().Account;
	}
	return tempAccount;
};
Ext
		.onReady(function() {
			$("#managerAccount").val(account());
			$('input[type="text"]').each(
					function(){
						$(this).change(
							function(){
								$('#bankDateChange').val('true');
							}
						);
					}
				);
			$('#cancel').click(function(){
				if (confirm("修正的資料將不會送出,確定嗎?"))
					window.location.reload();
				});
			
			Ext.QuickTips.init();

			var proxy = new Ext.data.HttpProxy(
					{
						api : {
							create : '/ad/sys/com/control/publish/PayToUserService.php?action=create&managerAccount='
									+ account(),
							read : '/ad/sys/com/control/publish/PayToUserService.php?action=read&managerAccount='
									+ account(),
							update : '/ad/sys/com/control/publish/PayToUserService.php?action=update&managerAccount='
									+ account(),
							destroy : '/ad/sys/com/control/publish/PayToUserService.php?action=destroy&managerAccount='
									+ account()
						}
					});

			var writer = new Ext.data.JsonWriter({
				writeAllFields : true
			});

			this.store = new Ext.data.JsonStore({
				fields : [ "Pid", {
					name : "PayId",
					type : 'string'
				}, {
					name : "PayMoney",
					type : 'string'
				}, {
					name : "PayDate",
					type : 'date'
				// ,dateFormat : 'Y/m/d'
				}, {
					name : "Status",
					type : 'boolean'
				} ],
				proxy : proxy,
				writer : writer,
				// url :
				// "/ad/sys/com/control/publish/UserService.php?action=queryAllPayToUserDateByAccount&managerAccount="
				// + account(),
				root : "row",
				remoteSort : false,
				totalProperty : 'count',
				messageProperty : 'msg',
				successProperty : 'success',
				autoLoad : false,
				autoSave : false,
				listeners : {
					exception : function(proxy, type, action, options,
							response, arg) {
						var result = Ext.decode(response.responseText);
						if (!result.success) {
							Ext.MessageBox.alert('錯誤！', result.msg);
						}
					},
					save : function(store) {
						store.reload(store.lastOptions);
					}
				}
			});

			// Various editors for the related fields:
			var textFieldEditor = {
				xtype : 'textfield',
				allowBlank : false,
				blankText : '此欄不可空白',
				minLength : 2,
				minText : '最少要填入{0}個字元',
				maxLength : 20,
				maxText : '最多只能填入{0}個字元'
			};
			var numberFieldEditor = {
				xtype : 'textfield',
				allowBlank : false,
				blankText : '此欄不可空白',
				regex : /[0-9]/
			};
			var genderFieldEditor = {
				xtype : 'combo',
				triggerAction : 'all',
				forceSelection : true,
				displayField : 'label',
				valueField : 'id',
				mode : 'local',
				store : {
					xtype : 'jsonstore',
					fields : [ 'id', 'label' ],
					data : [ {
						id : '0',
						label : '已付款'
					}, {
						id : '1',
						label : '未付款'
					} ]
				}
			};

			var dobFieldEditor = {
				xtype : 'datefield',
				allowBlank : false,
				blankText : '此欄不可空白',
				editable : false
			};

			var epaperFieldEditor = {
				xtype : 'checkbox'
			};

			var epaperRenderer = function(value) {
				if (value) {
					return '<input type="checkbox" checked />';
				} else {
					return '<input type="checkbox" />';
				}
			}

			var columns = new Ext.grid.ColumnModel({
				columns : [ new Ext.grid.RowNumberer({
					header : 'No.',
					dataIndex : 'Pid'
				}), {
					name : 'PayId',
					dataIndex : 'PayId',
					header : '付款編號',

					sortable : true,
					width : 80,
					editor : textFieldEditor
				}, {
					name : 'PayMoney',
					dataIndex : 'PayMoney',
					header : '給付金額',

					sortable : true,
					width : 50,
					editor : numberFieldEditor
				}, {
					name : 'PayDate',
					dataIndex : 'PayDate',
					header : '給付日期',
					sortable : true,
					width : 80,
					editor : dobFieldEditor,
					renderer : Ext.util.Format.dateRenderer('Y年m月d日')
				}, {
					name : 'Status',
					dataIndex : 'Status',
					header : '已付款',

					sortable : false,
					width : 80,
					editor : epaperFieldEditor,
					renderer : epaperRenderer
				} ],
				defaults : {
					resizable : false
				}
			});

			// Insert record
			var insertRecord = function() {
				var defaultRec = {
					id : 0,
					PayId : '',
					PayMoney : '0',
					PayDate : '',
					Status : false
				};
				var newRecord = new store.recordType(defaultRec);
				var lastIndex = store.getCount();
				store.insert(lastIndex, newRecord);
				grid.startEditing(lastIndex, 1);
			};

			// Delete record
			var deleteRecord = function() {
				var selectedCell = grid.getSelectionModel().getSelectedCell();
				if (selectedCell == null) {
					return;
				}
				var rowIndex = selectedCell[0];
				var targetRecord = store.getAt(rowIndex);
				store.remove(targetRecord);
				store.save();
			};

			// Row editor
			var rowEditor = new Ext.ux.grid.RowEditor({
				saveText : '確定',
				cancelText : '取消',
				commitChangesText : '請按下「確定」鈕'
			});

			// Save changes
			var saveChanges = function() {
				var modifiedRecords = store.getModifiedRecords();
				var modifiedRecNum = modifiedRecords.length;

				if (modifiedRecNum == 0){
					if ($('#bankDateChange').val() == 'true') {
						if (!confirm("已修改銀行資料，確定送出嗎？")) {
							return;
						}
						$('form')[0].submit();
					}
					return;
				}
				Ext.MessageBox.confirm('變更資料', '您確定要修改' + modifiedRecNum
						+ '筆記錄嗎？', function(btnLabel) {
					if (btnLabel == 'yes') {
						grid.stopEditing();
						store.save();
						if ($('#bankDateChange').val() == 'true') {
							if (!confirm("已修改銀行資料，確定送出嗎？")) {
								return;
							}

							$('form')[0].submit();
						}
					}

				});// eo confirm()
			}

			// Reject changes
			var rejectChanges = function() {
				var modifiedRecords = store.getModifiedRecords();
				var modifiedRecNum = modifiedRecords.length;

				if (modifiedRecNum == 0)
					return;

				Ext.MessageBox.confirm('變更資料', '您確定要復原' + modifiedRecNum
						+ '筆記錄嗎？', function(btnLabel) {
					if (btnLabel == 'yes')
						store.rejectChanges();
				});// eo confirm()
			}

			var paginTB = {
				xtype : 'paging',
				store : store,
				pageSize : 10,
				displayInfo : true,
				items : [ '-', {
					xtype : 'button',
					text : '還原',
					handler : rejectChanges,
					scope : this
				} ]
			};

			var grid = new Ext.grid.EditorGridPanel({
				title : '付款資訊',
				width : '100%',
				height : 280,
				store : store,
				viewConfig : {
					forceFit : true
				},
				colModel : columns,
				plugins : [ rowEditor ],
				// tbar : {
				// xtype : 'toolbar',
				// frame : true,
				// border : false,
				// padding : 2,
				// items : [ {
				// xtype : 'button',
				// text : '插入新資料',
				// iconCls : 'insertBtn',
				// handler : insertRecord,
				// scope : this
				// }, {
				// xtype : 'button',
				// text : '刪除資料',
				// iconCls : 'removeBtn',
				// handler : deleteRecord,
				// scope : this
				// } ]
				// },
				bbar : paginTB
			});
			grid.render('grid');

			store.load({
				params : {
					start : 0,
					limit : 10
				}
			});
			Ext.fly("search").on("click", function() {
				insertRecord();
			});
			Ext.fly("changeDateCheck").on("click", function() {
				saveChanges();
			});

		});
